package com.wangrui.test;

import com.wangrui.dao.UserMapper;
import com.wangrui.entity.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;

public class MyBatisTest02 {

    /**
     * 获得MyBatis SqlSessionFactory
     * SqlSessionFactory负责创建SqlSession，一旦创建成功，就可以用SqlSession实例来执行映射语句，commit，rollback，close等方法。
     *
     * @return
     */
    private static SqlSessionFactory getSessionFactory() {
        SqlSessionFactory sessionFactory = null;
        String resource = "configuration.xml";
        try {
            sessionFactory = new SqlSessionFactoryBuilder().build(Resources
                    .getResourceAsReader(resource));
        } catch (IOException e) {

            e.printStackTrace();
        }
        return sessionFactory;
    }

    public static void main(String[] args) {
        SqlSession sqlSession = getSessionFactory().openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.findById("1");
        System.out.println(user.getName());
        System.out.println(user.getExeName());
    }

    @Test
    public void testAdd() {
        SqlSessionFactory factory = getSessionFactory();
        //默认是手动提交的
        SqlSession session = factory.openSession();

        String statement = "com.myBatis.userMapper2.addUser";
        int insert = session.insert(statement, new User("KK", 23));
        //提交
        session.commit();
        session.close();
        System.out.println(insert);
    }

    @Test
    public void testDelete() {
        SqlSessionFactory factory = getSessionFactory();
        //默认是手动提交的
        SqlSession session = factory.openSession();

        String statement = "com.myBatis.userMapper2.deleteUser";
        int insert = session.delete(statement, 1);
        //提交
        session.commit();
        session.close();
        System.out.println(insert);
    }
}
